console.log("Starting...");
var 	sys = 		require('sys')
, 		url = 		require('url')
, 		app = 		require('http').createServer(handler)
,		qstr = 		require('querystring')
,		fs = 		require('fs')
,		io = 		require('socket.io').listen(app)
//,		db = 		require("mongojs").connect("localhost", ["myUsers"])
//,		csv = 		require('csv')
;
// do a self made event for saving user - data
// hacksparrow.com/node-js-eventemitter-tutorial.html
//
// flood prevention (1msg / sec)

var 	defaultmessage = 	"welcome to /dev/null"
,		secondspermsg = 	2
,		msgsize = 			160
,		clienttimeout = 	120
;

var 	users = 			new Array();
var 	startuptime = 		+new Date();

// New User Example
// users[0] = new Object();
// users[0]["socketiokey"] = SOCKETIO.KEY;
// users[0]["commkey"] = COMM.KEY; // Internal communication key (connection lost)
// users[0]["username"] = USERNAME;
// users[0]["lastmessage"] = Time of Last Message (+ clienttimeout = definitely disconnect)


app.listen(80);

function handler(req, res) {
		var now = new Date();
		var body = "";
		var afterpath = url.parse(req.url).pathname;
		var url_parts = url.parse(req.url, true);
		req.on('data', function (chunk) {
			body += chunk;
		});
	
	switch(afterpath) {
	case '/kinetic/':
		index = fs.readFileSync('libs/kinetic.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/jquery/':
		index = fs.readFileSync('libs/jquery.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/jqueryui/':
		index = fs.readFileSync('libs/jqueryui.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/jquerymobile/':
		index = fs.readFileSync('libs/jquerymobile.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/jquerymobilecss/':
		index = fs.readFileSync('libs/jquerymobile.css');
		res.writeHead(200, {'Content-Type': 'text/css'});
		res.end(index);
		break;
	case '/modernizr/':
		index = fs.readFileSync('libs/modernizr.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/style/':
		index = fs.readFileSync('libs/style.css');
		res.writeHead(200, {'Content-Type': 'text/css'});
		res.end(index);
		break;
	case '/my/':
		index = fs.readFileSync('libs/my.js');
		res.writeHead(200, {'Content-Type': 'text/javascript'});
		res.end(index);
		break;
	case '/cucumber/':
		/* oh cucumbers, lets see for GET's .. hehe */
		if(req.method=='GET'){
			var url_parts = url.parse(req.url, true);
			console.log(url_parts.query);
			fs.appendFile('httpreq.log', url_parts.query, function (err) {
				if (err) throw err;
			});
			index = fs.readFileSync('libs/index.html');
			res.writeHead(200, {'Content-Type': 'text/html'});
			res.end(index); 
		} else {
			res.writeHead(200, {'Content-Type': 'text/plain'});
			res.end(defaultmessage);
		}
		break;
	default:
		res.writeHead(200, {"Content-Type": "text/plain"});
		res.write(defaultmessage);
		res.end();
		break;
	}
};


io.sockets.on('connection', function (socket) { //gets fired after a client connects
//socket specific code 
var		connecttime = 		new Date().getTime();
var		lastmessage = 		new Date().getTime();
var 	nickname = 			'guest' + connecttime;
var		lastMessageDelta = 	0;
var		gavenick = 			false;

	
	socket.on('hello', function () { // Init connection
		console.log('hello from client');
		socket.emit('reHello', 'Welcome to ChatBox nodejs ChatServer v0.1');
		socket.emit('msgsize', msgsize);
	});
	
	socket.on('disconnect', function() {
		connecttime = 		null;
		lastmessage = 		null;
		nickname = 			null;
		lastMessageDelta = 	null;
		
		console.log(socket.id + 'disconnected');
	});
	
	socket.on('msgsize', function() {
		socket.emit('msgsize', msgsize);
	});
	
	socket.on('chatmessage', function (data) { 
		if (data.length > 0 && data.length < msgsize && lastMessageDelta < secondspermsg){
			if (data.charAt(0) == '/'){ // check for Commands
				console.log(data);
				var dataSplit = data.split(":", 2); // Split Command:Text into two Variables
				var command = dataSplit[0];
				var text = dataSplit[1];
				console.log(socket.id + '::' + command + '::' + text);
				
				switch(command) { // do something with that command (and text)
				case '/help':
					socket.emit('sysMsg', '<hr>');
					
					socket.emit('sysMsg', 'HELP, I need somebody!');
					socket.emit('sysMsg', '&#47;nick:NICKNAME - set nickname NICKNAME ');
					socket.emit('sysMsg', 'Messagesize:' + msgsize);
					
					socket.emit('sysMsg', '<hr>');
					break;
				case '/serverinfo':
					socket.emit('sysMsg', 'ChatBox nodejs ChatServer v0.1');
					socket.emit('sysMsg', 'Messagesize:' + msgsize);
					socket.emit('sysMsg', 'MaxMessages:' + secondspermsg);
					var elapsed = Math.floor((+new Date() - startuptime) / 1000);
					console.log('Uptime: ' + elapsed + 'seconds');
					socket.emit('sysMsg', 'Uptime:' + elapsed + 'seconds');
					socket.emit('sysMsg', 'Nick: ' + nickname);
					break;
				case '/img':
					break;
				case '/nick':
					var regx = new RegExp('^[a-zA-Z0-9]+$');
					console.log('::' + text + '::');
					console.log(regx.test(text));
					if (regx.test(text) == true) {
						nickname = text;
						gavenick = true;
						socket.emit('sysMsg', text + ' sounds nice! Welcome!');
						socket.broadcast.emit('sysMsg', nickname + ' has joined!')
					} else {
						socket.emit('sysMsg', 'This one is not allowed, please try again.');
						socket.emit('nick');
					}
					break;
				default:
					socket.emit('sysMsg', 'unknown command. try &#47;help');
					break;
				}
			} else { //if there is no command .. then it must be a ChatMessage
				if (gavenick == true){ //check if a nickname was given in this session
					socket.broadcast.emit('chatmessage', '<b>' + nickname + ':</b>' + data); // Broadcast to others
					socket.emit('chatmessage', '<b>' + nickname + ':</b>' + data); // Broadcast to self
				} else {
					socket.emit('sysMsg', 'Please set a nick.');
				}
				
			} 
		} else { //if the Client sends Zero Data.. log it.
			console.log('0 Data send');
			socket.emit('sysMsg', 'Messagesize problem! Message not delivered.');
		}
	lastMessageDelta = 0;
	});
	
	
});

console.log("Server started");
